package com.taobao.diamond.util;

import com.taobao.diamond.common.Constants;
import com.taobao.diamond.manager.DiamondManager;
import com.taobao.diamond.manager.DiamondPubManager;
import com.taobao.diamond.manager.impl.DefaultDiamondManager;
import com.taobao.diamond.manager.impl.DefaultDiamondPubManager;
import com.taobao.diamond.manager.impl.HttpSimpleClient;
import com.taobao.diamond.manager.impl.ServerHttpAgent;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;

/**
 * <p></p>
 * User: <a href="mailto:yanmingming1989@163.com">严明明</a>
 * Date: 15/7/23
 * Time: 下午3:22
 */
public class DiamondUtil {

    private static final Log logger = LogFactory.getLog(DiamondUtil.class);

    private static DiamondPubManager diamondPubManager = new DefaultDiamondPubManager();

    /**
     * Spring 容器初始bean时调用该方法
     *
     * @throws Exception
     */
    public void init() throws Exception {
    }

    public void destroy() {
    }

    /**
     * 指定从Diamond上读取信息，任何的本地缓存都跳过
     *
     * @param group  数据的group
     * @param dataId 数据的DataId
     * @return
     */
    public static String getServerDataIdContent(String group, String dataId) {
        checkNotNull(new String[]{group, dataId});
        ServerHttpAgent agent = new ServerHttpAgent();
        String url = getUriString(dataId, group);
        HttpSimpleClient.HttpResult result = null;
        try {
            result = agent.httpGet(url, null, "GBK", 3000L);
        } catch (IOException ioe) {
            logger.warn(new StringBuilder().append("[query-config] error, ").append(dataId).append(", ").append(group).append(", msg: ").append(ioe.toString()).toString());
            return null;
        }

        if (result != null && StringUtils.isNotBlank(result.content)) {
            logger.info(new StringBuilder().append("[query-config] ok. ").append(dataId).append(", ").append(group).toString());
            return result.content;
        }

        return null;
    }


    private static void checkNotNull(String[] params) {
        for (String param : params) {
            if (StringUtils.isBlank(param))
                throw new IllegalArgumentException("param cannot be blank");
        }
    }

    /**
     * 获取查询Uri的String
     *
     * @param dataId
     * @param group
     * @return
     */
    private static String getUriString(String dataId, String group) {
        StringBuilder uriBuilder = new StringBuilder();
        uriBuilder.append(Constants.HTTP_URI_FILE);
        uriBuilder.append("?");
        uriBuilder.append(Constants.DATAID).append("=").append(dataId);
        if (null != group) {
            uriBuilder.append("&");
            uriBuilder.append(Constants.GROUP).append("=").append(group);
        }
        return uriBuilder.toString();
    }

    /**
     * 从Diamond上读取可以读到的信息，如果网络超时，则杜本地SNAPSHOT
     *
     * @param group  数据的group
     * @param dataId 数据的DataId
     * @return
     */
    public static String getAvailableDataIdContent(String group, String dataId) {
        DiamondManager defaultDiamondManager = new DefaultDiamondManager(group, dataId, (com.taobao.diamond.manager.ManagerListener) null);
        String result = defaultDiamondManager.getAvailableConfigureInfomation(10 * 1000);
        return null == result ? "" : result;
    }


    /**
     * 更新指定DataId里面的指定行数据，如果存在则更新，如果不存在，则追加
     *
     * @param group
     * @param dataId
     * @param originLineContent 原始内容为null时，表示数据追加
     * @param newLineContent
     * @return
     */
    boolean publish(String group, String dataId, String originLineContent, String newLineContent) {
        return diamondPubManager.publish(group, dataId, originLineContent, newLineContent);
    }

    /**
     * 删除指定DataId里面的指定行数据
     *
     * @param group
     * @param dataId
     * @param content
     * @return
     */
    boolean unPublish(String group, String dataId, String content) {
        return diamondPubManager.unPublish(group, dataId, content);
    }

    /**
     * 更新指定DataId里面的所有数据，使用content进行覆盖
     *
     * @param group
     * @param dataId
     * @param content
     * @return
     */
    boolean publishAll(String group, String dataId, String content) {
        return diamondPubManager.publishAll(group, dataId, content);
    }


}
